package top.baselitch.liteorm;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

import top.baselitch.liteorm.annotation.Table;
import top.baselitch.liteorm.annotation.TableField;

public class TableModel {
    private String tableName;//表名称
    private Set<FieldModel> fieldModels;//字段集合
    private TableModel(Builder builder){
        this.tableName = builder.tableName;
        this.fieldModels = builder.fieldModels;
    }
    public static class Builder{
        private Class tableModelClass;
        private Field[] fields;
        private String tableName;//表名称
        private Set<FieldModel> fieldModels;//字段集合
        public <T> Builder(Class<T> tableModelClass){
            Utils.verifyTableModel(tableModelClass);
            this.tableModelClass = tableModelClass;
            this.fields = tableModelClass.getDeclaredFields();
        }
        public <T> TableModel builder(){
            parseTable();
            return new TableModel(this);
        }

        /**
         * 解析表
         */
        private void parseTable(){
            Table tableAnn = (Table) tableModelClass.getAnnotation(Table.class);
            this.tableName = tableAnn.value();
            fieldModels = new HashSet<>();
            for(Field field : fields){
                if(field.isAnnotationPresent(TableField.class)){
                    FieldModel fieldModel = new FieldModel.Builder(field).builder();
                    this.fieldModels.add(fieldModel);
                }
            }
        }
    }


    public String buildCreateSql(){
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE IF NOT EXISTS ");
        sb.append(tableName);
        sb.append(" (");
        int fieldLenth = fieldModels.size();
        int ind = 0;
        for(FieldModel fieldModel : fieldModels){
            sb.append(fieldModel.builderSql());
            sb.append(ind==fieldLenth-1?")":",");
            ind++;
        }
        return sb.toString();
    }

    public String getTableName() {
        return tableName;
    }
}
